/**
 * blog数据库操作
 */
 
var blog = {};

var mysql	= require('mysql');


blog.connection = new mysql.Client();
blog.connect = function (cb) {
	if (!blog.connection.connected) {
		blog.connection.host = '127.0.0.1';
		blog.connection.user = 'root';
		blog.connection.password = '';
		blog.connection.database = 'njs';
		blog.connection.connect(function (err) {
			cb(err);
		});
	}
	else {
		cb();
	}
}

/** 添加一行数据 */
blog.post = function (rows, cb) {
	var now = new Date().getTime() / 1000;
	blog.connection.query('INSERT INTO blog (title, body, timestamp, last_modified) VALUES (?, ?, ?, ?);',
		[rows.title, rows.body, now, now], function (err, resoult) {
		
		cb(err, resoult);
	});
}

/** 修改一行数据 */
blog.edit = function (rows, cb) {
	var now = new Date().getTime() / 1000;
	blog.connection.query('UPDATE blog SET title=?, body=?, last_modified=? WHERE id=? LIMIT 1;',
		[rows.title, rows.body, now, rows.id], function (err, resoult) {
		
		cb(err, resoult);
	});
}

/** 取指定ID的文章信息 */
blog.read = function (id, cb) {
	blog.connection.query('SELECT * FROM blog WHERE id=? LIMIT 1', [id], function (err, resoult) {
		cb(err, resoult);
	});
}

/** 取指定页的文章列表 */
blog.list = function (p, cb) {
	var pageSize = 5;
	blog.connection.query('SELECT * FROM blog ORDER BY last_modified DESC LIMIT ?,?',
		[((p - 1) * pageSize), pageSize], function (err, resoult) {
		cb(err, resoult);
	});
}


/** 模块输出 */
module.exports = blog;
exports.ver = '0.1';
exports.mysql = mysql;
/*
exports.connect = blog.connect;
exports.post = blog.post;
*/

// 测试
